<template>
  <div id="homepage">
      <div class="bodyContent">
        <div class="centerCont">
          <!-- 上部分 -->
          <div class="topCont">
            <p>当前市场规模</p>
            <h1>$ {{ this.allWordPool | format_number }}</h1>
            <div class="blockNumber">
              Elabank Pool: ${{ "1877545.12" | format_number }}
            </div>
          </div>
          <!-- 列表部分 -->
          <div>
            <ul class="listHeader">
              <li style="flex: 1">Assets</li>
              <li style="flex: 1">Pool Size</li>
              <li style="flex: 1">Total rewards</li>
              <li style="flex: 1">rewards APY</li>
              <li style="flex: 1">Your Balance</li>
              <li style="flex: 1">Earned</li>
              <li class="listBtnCont"></li>
            </ul>

            <ul class="listBody">
              <li style="flex: 1">NoMintRewardPool</li>
              <li style="flex: 1">{{ this.nrPool.totalSupply | format_number }} CFN</li>
              <li style="flex: 1">¥ {{ "0" | format_number }}</li>
              <li style="flex: 1">rewards APY</li>
              <li style="flex: 1">{{this.nrPool.balanceOf | format_number}} CFN</li>
              <li style="flex: 1">{{this.nrPool.earned | format_number}} BTR</li>
              <li class="listBtnCont">
                <span class="listBtn" @click="tiqujiangToken()">领取奖励</span>
                <span class="listBtn" @click="routerUp('/Products')">质押</span>
                <span class="listBtn" @click="routerUp('/Extract')">提取</span>
              </li>
            </ul>

            <div class="bottonCont">
              <span class="creatButton" @click="routerUp('/CreatAPool')">创建你的奖励池</span>
            </div>
          </div>
        </div>
        <footer-con />
      </div>
    </div>
  </div>
</template>
<script>
import FooterCon from "@/containers/common/Footer.vue";
const Web3Utils = require("web3-utils");

let NoMintRewardPool = require("../NoMintRewardPool.json");
export default {
  data() {
    return {
      myAddress: "",
      network: "",
      allWordPool: 1888666554.99,
      nrPool: {
        totalSupply: 0,
        balanceOf: 0,
        earned: 0,
        listYuan: [
        {
          name: 'NoMintRewardPool',
          address: '0xB8fCB3C1350ECafb927280a613B01B7B07844b52',
          poolSize: '0',
          zhiyaAddress: '0x17f94db94d9d6f10267c3bb9a35dafd7825de0fd',
          zhiyaDanwei: 'CFN',
          youBalance: '0',
          youEarned: '0',
          huodeAddress: '0x82d30e24708318c5da73accb7cebc1d0a1d86276',
          huodeDanwei: 'BTR'
        }
      ]
      },
    };
  },
  components: {
    "footer-con": FooterCon,
  },
  methods: {
    // 路由跳转
    routerUp(uri) {
      this.$router.push({
        path: uri,
      });
    },
    initFunc() {
      //用来判断你是否安装了metamask
      if (!window.web3 && !window.ethereum) {
        this.$parent.metaMaskActiveFunc(0);
        window.alert("请先安装MetaMask钱包插件！"); //如果没有会去提示你先去安装
        return;
      }
      if (!window.myWeb3) {
        this.$parent.metaMaskActiveFunc(1);
        return;
      } else {
        this.contractMetaMaskFunc();
      }
    },
    async contractMetaMaskFunc() {
      let web3Provider = null;
      //用来判断你是否安装了metamask
      if (!window.web3 && !window.ethereum) {
        this.$parent.metaMaskActiveFunc(0);
        window.alert("请先安装MetaMask钱包插件！"); //如果没有会去提示你先去安装
        return;
      }
      // 检查metamask是否连接上了网络
      if (window.ethereum) {
        web3Provider = window.ethereum;
        try {
          // 请求用户授权
          console.log("请求用户授权");
          await window.ethereum.enable();
          console.log("授权完成");
        } catch (error) {
          // 用户不授权时
          this.$parent.metaMaskActiveFunc(2);
          console.error("用户拒绝帐户访问");
          return;
        }
      } else if (window.web3) {
        // 老版 MetaMask Legacy dapp browsers...
        web3Provider = window.web3.currentProvider;
      }

      if (!window.myWeb3) {
        window.myWeb3 = new Web3(web3Provider);
      }

      console.log("window.web3", window.web3);
      console.log("window.myWeb3", window.myWeb3);

      //这个是判断你有没有登录，coinbase是你此时选择的账号
      if (!window.myWeb3.eth.coinbase) {
        this.$parent.metaMaskActiveFunc(4);
        window.alert("请先激活MetaMask！");
        return;
      }

      // 获取主网
      let network = window.myWeb3.version.network;
      this.$parent.metaMaskActiveFunc(3);
      this.$parent.networkFunc(network);
      console.log("network", network); // 1 主网 3 水管测试 21 elatest

      // 获取我的地址
      this.myAddress = window.myWeb3.eth.coinbase.toLowerCase();
      console.log("myAddress", this.myAddress);
      this.$root.bus.$emit("changeHeaderAddressBus", { val: this.myAddress });

      var MyContract = window.myWeb3.eth.contract(NoMintRewardPool.abi);
      var MyContractErc20 = window.myWeb3.eth.contract(
        NoMintRewardPool.erc20Abi
      );

      // 使用合约地址实例化合约
      window.contractInstance = MyContract.at(NoMintRewardPool.contractAddress);
      window.contractInstanceErc20 = MyContractErc20.at(
        NoMintRewardPool.yabiAddress
      );
      console.log(
        "window.contractInstance",
        window.contractInstance,
        "window.contractInstanceErc20",
        window.contractInstanceErc20
      );

      // 资⾦池中质押token总数
      window.contractInstance.totalSupply((error, log) => {
        if (!error) {
          console.log("totalSupply toString", log.toString());
          console.log("totalSupply fromWei", Web3Utils.fromWei(log.toString()));
          this.nrPool.totalSupply = Web3Utils.fromWei(log.toString());
        }
      });

      // 我的质押token余额
      window.contractInstance.balanceOf(this.myAddress, (error, log) => {
        if (!error) {
          console.log("balanceOf toString", log.toString());
          console.log("balanceOf fromWei", Web3Utils.fromWei(log.toString()));
          this.nrPool.balanceOf = Web3Utils.fromWei(log.toString());
        }
      });

      // 从上次获取奖励到当前时间，可以获得奖励的总数
      window.contractInstance.earned(this.myAddress, (error, log) => {
        if (!error) {
          console.log("earned toString", log.toString());
          console.log("earned gwei", Web3Utils.fromWei(log.toString(),'gwei'));
          // this.nrPool.earned = Web3Utils.fromWei(log.toString());
           this.nrPool.earned = (log.toString()/100000000);
        }
      });

      // 上次更新奖励的时间，单位s，区块时间
      window.contractInstance.lastUpdateTime((error, log) => {
        if (!error) {
          console.log("lastUpdateTime", log.toString());
        }
      });
    },
    tiqujiangToken(){
      let _this = this
        window.contractInstance.getReward(
          function (error3, resHash) {
            if (error3) throw error3;
            console.log("getReward", resHash.toString());
            _this.open(resHash.toString());
          }
        );
    },
    open(hash) {
        this.$alert('交易hash： '+hash+' ', '领取提示', {
          confirmButtonText: '确定',
          callback: action => {
            // 从上次获取奖励到当前时间，可以获得奖励的总数
            window.contractInstance.earned(this.myAddress, (error, log) => {
              if (!error) {
                this.nrPool.earned = (log.toString()/100000000);
              }
            });
          }
        });
      }
  },
  mounted() {
    this.initFunc();

    this.$root.bus.$on("incremented", ({ num, deg }) => {
      this.contractMetaMaskFunc();
    });
  },
  computed: {},
  filters: {
    format_number: function (nStr) {
      nStr += "";
      let x = nStr.split(".");
      let x1 = x[0];
      let x2 = x.length > 1 ? "." + x[1] : "";
      var rgx = /(\d+)(\d{3})/;
      while (rgx.test(x1)) {
        x1 = x1.replace(rgx, "$1" + "," + "$2");
      }
      return x1 + x2;
    },
  },
};
</script>
<style scoped lang='scss'>
@import "@/asserts/styles/homePage/homePage.scss";
</style>